package com.stylefeng.guns.rest.modular.artitle.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.baomidou.mybatisplus.mapper.Condition;
import com.stylefeng.guns.rest.common.Constant;
import com.stylefeng.guns.rest.common.base.Constans;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.exception.BussinessException;
import com.stylefeng.guns.rest.common.persistence.dao.ArtitleMapper;
import com.stylefeng.guns.rest.common.persistence.model.Article;
import com.stylefeng.guns.rest.common.persistence.model.FileEntity;
import com.stylefeng.guns.rest.common.utils.TextUtil;
import com.stylefeng.guns.rest.modular.artitle.controller.dto.ArticleDetailResponse;
import com.stylefeng.guns.rest.modular.artitle.controller.dto.PlayInfoBean;
import com.stylefeng.guns.rest.modular.attent.controller.dto.AttentHotRequest;
import com.stylefeng.guns.rest.modular.catalogy.controller.dto.ArticleListResponse;
import com.stylefeng.guns.rest.modular.catalogy.controller.dto.CatalogyListRequest;
import com.stylefeng.guns.rest.modular.catalogy.service.CatalogyService;
import com.stylefeng.guns.rest.modular.keyword.controller.dto.KeywordRequestBody;
import com.stylefeng.guns.rest.modular.users.controller.dto.UserInfoRequest;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by ASUS-PC on 2018/6/26.
 */
@Service
public class ArticleService {
    @Autowired
    ArtitleMapper artitleMapper;
    @Autowired
    FileService fileService;
    @Autowired
    CatalogyService catalogyService;
    private final Log logger = org.apache.commons.logging.LogFactory.getLog(this.getClass());
    //或者用户最新的五个文章
    public List<Article> findHotUserArticles(int userId){
        return artitleMapper.findHotUserArticles(userId);
    }

    //获取文章详情
    public ArticleDetailResponse getArticleDetail(int articleId){
        Map<String ,Object> data = new HashedMap();
        data.put("articleId",articleId);
        return artitleMapper.queryArticleDetail(data);
    }
    //插入文章
    public boolean insertArtitle(Article article){
        return artitleMapper.insert(article)==1 ? true:false;
    }

    //更新文章的观看记录
    public void addViewNum(int id,int num){
        Map<String ,Object> data = new HashedMap();
        data.put("id",id);
        data.put("num",num);
        artitleMapper.addViewNum(data);
    }

    //根据查询页数获取用户的创作文章
    public List<ArticleDetailResponse> userArticleList(AttentHotRequest request){
        Map<String ,Object> data = new HashedMap();
        data.put("userId",request.getUserId());
        data.put("pageIndex",(request.getPage()-1)*request.getSize());
        data.put("pageSize",request.getSize());
        return artitleMapper.userArticleList(data);
    }

    //获取用户的所有创作文章
    public List<ArticleDetailResponse> userAllList(AttentHotRequest request){
        Map<String ,Object> data = new HashedMap();
        data.put("userId",request.getUserId());
        return artitleMapper.userAllList(data);
    }

    //获取用户的所有创作文章
    public List<Article> userAllArticleList(UserInfoRequest request){
        return artitleMapper.selectList(Condition.create().eq("user_id" , request.getUserId()));
    }

    //获取用户的创作文章
    public List<Article> getUserArticleByCare(AttentHotRequest request){
        Map<String ,Object> data = new HashedMap();
        data.put("userId",request.getUserId());
        return artitleMapper.getUserArticleByCare(data);
    }

    //获取根据关键词
    public List<ArticleListResponse> findArtitleByKeyword(KeywordRequestBody request){
        Map<String ,Object> data = new HashedMap();
        data.put("keyword",request.getKeyword());
        data.put("pageIndex",(request.getPage()-1)*request.getSize());
        data.put("pageSize",request.getSize());
        return artitleMapper.findArtitleByKeyword(data);
    }

    //查询文章
    public Article queryArtitle(int id){
        List<Article> list = artitleMapper.selectList(Condition.create().eq("id" ,id));
        return list.get(0);
    }
    //更新分享次数
    public int uqdateShareNum(Article article){
        return artitleMapper.updateById(article);
    }

    //删除文章
    public boolean deletArtitle(int artitleId){
        return artitleMapper.delete(Condition.create().eq("id" , artitleId))>0 ? true:false;
    }

    //删除服务器上的视频文件
    public void deleVedioFile(int artitleId){
        List<Article> list = artitleMapper.selectList(Condition.create().eq("id" ,artitleId));
        if(list!=null && list.size()>0){
            FileEntity fileEntity = fileService.searchById(list.get(0).getFileId());
            if(fileEntity!=null){
                File file = new File(Constant.FILE_PATH+fileEntity.getFilePath());
                if (file.exists()){
                    file.delete();
                }
            }
        }
    }

    //通过文章id查询video
    public Article getArticleById(int articleId){
        List<Article> mList = artitleMapper.selectList(Condition.create().eq("id" , articleId));
        if(mList!=null && mList.size()>0){
            return mList.get(0);
        }else {
            return null;
        }
    }

    //获取时下流行的视频列表
    public List<Article> getFactionList(){
        return artitleMapper.getFactionList();
    }

    //查询目前没有封面图片的视频
    public List<Article> getVedioListNotImage(){
        return artitleMapper.getVedioListNotImage();
    }


    //查询所有视频列表，获取默认的视频封面，更新
    public void updateSSOUrl(){
        List<Article> responses = getVedioListNotImage();
        if(responses!=null && responses.size()>0){
            for (int i = 0; i <responses.size() ; i++) {
                Article a = responses.get(i);
                PlayInfoBean playInfoBean = getPlayInfoBeanFromVideoId(a.getVedioId());
                if(TextUtil.isEmpty(a.getBgImage())){
                    if(playInfoBean!=null){
                        a.setBgImage(playInfoBean.getVideoBase().getCoverURL());
                    }
                }
                if(a.getVideoLength() == 0){
                    if(playInfoBean!=null){
                        String duration = playInfoBean.getVideoBase().getDuration();
                        a.setVideoLength((int)(Double.parseDouble(duration)*1000));
                    }
                }
                uqdateShareNum(a);
            }
        }
    }

    //获取视频信息（）
    public PlayInfoBean getPlayInfoBeanFromVideoId(String videoId){
        GetPlayInfoResponse response = null;
        GetPlayInfoResponse.PlayInfo p = null;
        GetPlayInfoResponse.VideoBase videoBase = null;
        PlayInfoBean playInfoBean = new PlayInfoBean();
        try {
            response = getPlayInfo(videoId);
            videoBase = response.getVideoBase();
            playInfoBean.setVideoBase(videoBase);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
            //播放地址
            for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
                logger.info("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "-----"+playInfo.getDefinition()+"---"+playInfo.getDuration());
                if("OD".equals(playInfo.getDefinition())){
                    p = playInfo;
                    playInfoBean.setPlayInfo(p);
                    return playInfoBean;
                }
            }
        } catch (Exception e) {
            logger.info("ErrorMessage = " + e.getLocalizedMessage());
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }
        return null;
    }

    /*获取播放地址函数*/
    public GetPlayInfoResponse getPlayInfo(String vedidId) throws Exception {
        DefaultAcsClient client = initVodClient(Constans.ALIYUN_ACCESS_ACCOUNT,Constans.ALIYUN_ACCESS_SCRECT);
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(vedidId);
        request.setStreamType("video");
        request.setFormats("mp4");
        /*request.setFormats("mp4");
        request.setStreamType("video");
        request.setDefinition("HD");*/
        return client.getAcsResponse(request);
    }

    /**
     * 初始化阿里云oss上传服务
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws ClientException
     */
    public  DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        String regionId = "cn-shanghai";  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }


}
